<template>
  <div class="data-config">
    <el-form size="mini" class="customForm" label-width="90px">
      <el-form-item label="数据类型">
        <tm-radio :data="typeList" v-model="option.cptDataForm.dataSource"/>
      </el-form-item>
      <el-form-item label="轮询" v-show="option.cptDataForm.dataSource !== 1">
        <el-switch v-model="dataPollEnable" active-text="开启" inactive-text="关闭"/>
      </el-form-item>
      <el-form-item label="静态数据" v-show="option.cptDataForm.dataSource === 1">
        <div class="editor-tool">
          <el-button type="info" @click="showDialog(2, $event)">弹窗编辑</el-button>
        </div>

        <b-ace-editor v-model="dataJson" theme="vibrant_ink" :styles="{border: 'none'}"/>

      </el-form-item>
      <template v-if="option.cptDataForm.dataSource === 2">
        <el-form-item label="数据源">
          <el-select v-model="option.cptDataForm.dataSourceId" clearable>
            <el-option v-for="item in sourceList" :key="item.id" :label="item.sourceName" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="sql">
          <codemirror class="code"  v-model="option.cptDataForm.sql" :options="cmOptions"/>
        </el-form-item>
      </template>

      <template v-if="option.cptDataForm.dataSource === 3">
        <el-form-item label="数据集">
          <el-button type="info" @click="showDialog(1, $event)">
            {{option.cptDataForm.dateSetName || '请选择数据集'}}
          </el-button>
        </el-form-item>
      </template>

      <el-form-item label="结果处理" v-if="option.cptDataForm.dataSource !== 1">
        <el-button type="info" @click="showDialog(3, $event)">设置函数</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" style="width: 100%" @click="onRefresh()">刷新应用</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据集选择 -->
    <simple-dialog2 v-bind.sync="dialog" theme="dark" @on-ok="onDialogOk"/>

    <!-- 静态数据编辑 -->
    <simple-dialog2 title="静态数据编辑" :origin="modelOrigin" :visible.sync="modal" width="50%">
      <b-ace-editor height="650" v-model="modalJsonStr" theme="vibrant_ink" :styles="{border: 'none'}"/>
      <template v-slot:footer>
        <el-button size="small" @click="modal = false">取消</el-button>
        <el-button size="small" type="primary" @click="onEditOk">确定</el-button>
      </template>
    </simple-dialog2>
  </div>
</template>

<script>
import tmRadio from '@/package/components/tm-radio'
import {isJSON} from "@/utils/myutils";
import {codemirror} from "vue-codemirror"

import {postReportReportdatasourceListAll} from '@/api/dataSource'
import dialogMixin from "@/components/common/dialog/dialog-mixin"
import tmDatasetPanel from "@/package/components/tm-dataset-panel"
import tmScriptPanel from "@/package/components/tm-script-panel"
import Editor from 'bin-ace-editor'
import {afterFunStr} from "@/utils/FunUtil";

require('brace/mode/json')
require('brace/snippets/json')
require('brace/theme/vibrant_ink')

export default {
  name: 'data-config',
  cnName: '数据-配置',
  mixins: [dialogMixin],
  components: {
    tmRadio,
    codemirror,
    bAceEditor: Editor
  },
  props: {
    option: Object
  },

  data() {
    return {
      typeList: [
        {label: '静态', value: 1},
        {label: 'sql', value: 2},
        {label: '数据集', value: 3}
      ],
      cmOptions: {
        tabSize: 4, // tab的空格个数
        theme: 'dracula', //主题样式
        lineNumbers: true, //是否显示行数
        lineWrapping: true, //是否自动换行
        styleActiveLine: true, //line选择是是否加亮
        matchBrackets: true, //括号匹配
        mode: 'text/x-sparksql', //实现javascript代码高亮
        readOnly: false, //只读

        keyMap: 'default',
        extraKeys: { tab: 'autocomplete' },
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        hintOptions: {
          completeSingle: false,
          tables: {},
        },
      },
      sourceList: [],
      modal: false,
      modalJsonStr: '',
      modelOrigin: {}
    }
  },
  computed: {
    dataPollEnable: {
      get() {
        return !!(
            this.option.cptDataForm &&
            this.option.cptDataForm.pollTime &&
            this.option.cptDataForm.pollTime !== 0
        );
      },
      set(newValue) {
        if (newValue) {
          this.option.cptDataForm.pollTime = 8;
        } else {
          this.option.cptDataForm.pollTime = 0;
          this.refreshCptData(); //清除定时器
        }
        return newValue;
      },
    },
    dataJson: {
      get() {
        if (isJSON(this.option.cptDataForm.dataText)) {
          return JSON.stringify(JSON.parse(this.option.cptDataForm.dataText), null, 2)
        } else {
          return '{}';
        }
      },
      set(newValue) {
        this.option.cptDataForm.dataText = newValue;
      }
    }
  },
  methods: {
    onRefresh() {
      if(this.option.cptDataForm.dataSource === 2) { // sql
        const dataSourceId = this.option.cptDataForm.dataSourceId
        const sql = this.option.cptDataForm.sql

        if(!dataSourceId) {
          this.$message.warning('数据源不能为空')
          return
        }
        if(!sql) {
          this.$message.warning('SQL不能为空')
          return
        }
      }
      this.refreshCptData()
    },
    refreshCptData() {
      this.$emit('refreshCptData');
    },
    async loadDict() {
      const res = await postReportReportdatasourceListAll({})
      this.sourceList = res || []
    },
    showDialog(type, evt) {
      this.currType = type
      if(type === 1) {
        this.onPick(evt)
      } else if(type === 2) {
        this.onEditShow(evt)
        return
      } else if(type === 3) {
        this.onScriptShow(evt)
      }
    },
    onDialogOk(data) {
      this.dialog.visible = false
      if(this.currType === 1) {
        this.onPickOk(data)
      } else if(this.currType === 3) {
        this.onScriptOk(data)
      }
    },
    onPick(evt) {
      const origin = {
        x: evt.pageX,
        y: evt.pageY
      }
      this.setDialog({
        title: '选择数据集',
        origin: origin,
        comp: tmDatasetPanel,
        props: {
          dataSetId: this.option.cptDataForm.dataSetId
        }
      })
    },
    onPickOk(data){
      const {dataSetId, dateSetName} = data
      this.option.cptDataForm.dataSetId = dataSetId
      this.option.cptDataForm.dateSetName = dateSetName

      this.refreshCptData()
    },

    onEditShow(evt) {
      const origin = {
        x: evt.pageX,
        y: evt.pageY
      }
      this.modelOrigin = origin
      this.modalJsonStr = this.dataJson
      this.modal = true
    },
    onEditOk() {
      this.dataJson = this.modalJsonStr
      this.modal = false
    },
    onScriptShow(evt) {
      const origin = {
        x: evt.pageX,
        y: evt.pageY
      }
      this.setDialog({
        title: '数据处理',
        origin: origin,
        comp: tmScriptPanel,
        props: {
          value: this.option.cptDataForm.dataHandle || afterFunStr,
          type: 'data'
        }
      })
    },
    onScriptOk(res) {
      this.option.cptDataForm.dataHandle = res
      this.onRefresh()
    }
  },
  mounted() {
    this.loadDict()
  }
}
</script>

<style lang="less" scoped>
.data-config {
}

.editor-tool {
  margin-bottom: 10px;
}
</style>
